from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from goods.models import SKU
from django_redis import get_redis_connection
import json,pickle,base64
from carts.utils import get_redis_carts,get_carts_from_cookies
# Create your views here.
class CartsView(View):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)

        if not all([sku_id,count]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少必传参数'
            })
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'商品不存在'
            })
        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'count有误'
            })
        if selected:
            if not isinstance(selected,bool):
                return JsonResponse({
                    'code':400,
                    'errmsg':'selected有误'
                })
        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            p1 = redis_conn.pipeline()
            p1.hincrby(
                'carts_%s' % request.user.id,
                sku_id,
                count
            )
            if selected:
                p1.sadd(
                    'selected_%s' % request.user.id,
                    sku_id
                )
            p1.execute()
            return JsonResponse({
                'code':0,
                'errmsg':'添加购物车成功'
            })
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                count += cart_dict[sku_id]['count']
            cart_dict[sku_id] = {
                'count':count,
                'selected':selected
            }
            cart_data = base64.b64decode(pickle.dump(cart_dict)).decode()
            response = JsonResponse({
                'code':0,
                'errmsg':'添加购物车成功'
            })
            response.set_cookie('carts',cart_data)
            return response

    def get(self,request):
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            cart_dict = {}
            for sku_id,count in item_dict.items():
                cart_dict[int(sku_id)] = {
                    'count':int(count),
                    'selected':sku_id in cart_selected
                }
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}
            # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * cart_dict.get(sku.id).get('count'),
            })

        # 渲染购物车页面
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })

    def put(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return JsonResponse({
                'code':400,
                'errmsg': '缺少必传参数'
            })
            # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg': 'sku_id不存在'
            })
                # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return JsonResponse({
                'code':400,
                'errmsg': 'count有误'
            })
                    # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({
                    'code':400,
                    'errmsg': 'selected有误'
                })
        user = request.user
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 因为接口设计为幂等的，直接覆盖
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 是否选中
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return JsonResponse({
                'code': 0,
                'errmsg': '修改购物车成功',
                'cart_sku': cart_sku
            })
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                # 将cookie_cart转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}
            # 因为接口设计为幂等的，直接覆盖
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }
            response = JsonResponse({'code': 0,
                                     'errmsg': '修改购物车成功',
                                     'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cart_data)

            return response

    def delete(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'商品不存在'
            })
        user = request.user
        if user.is_authenticated:
            # 用户未登录，删除redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除键，就等价于删除了整条记录
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': 0,
                                 'errmsg': '删除购物车成功'})
        else:
            # 用户未登录，删除cookie购物车
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                # 将cookie_cart转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': 0,
                                     'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cart_data)

            return response


class CartSelectAllView(View):
    def put(self,request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected',True)
        if selected:
            if not isinstance(selected,bool):
                return JsonResponse({
                    'code':400,
                    'errmsg':'参数selected有误'
                })
        user = request.user
        if user.is_authenticated:
            # 用户已登录，操作 redis 购物车
            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            sku_ids = item_dict.keys()

            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *sku_ids)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id, *sku_ids)

            return JsonResponse({'code': 0,
                                 'errmsg': '全选购物车成功'})
        else:
            # 用户未登录，操作 cookie 购物车
            cookie_cart = request.COOKIES.get('carts')
            response = JsonResponse({'code': 0,
                                     'errmsg': '全选购物车成功'})
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

                for sku_id in cart_dict.keys():
                    cart_dict[sku_id]['selected'] = selected

                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

                response.set_cookie('carts', cart_data)

            return response


class CartsSimpleView(View):

    def get(self, request):
        # 读取购物车数据，在去读取sku商品对象，构建响应参数
        # {14: {"count": 5, "selected": True}}
        cart_data = {}

        if request.user.is_authenticated:
            # 1、已登陆
            # redis_cart = {b"14": b"3"}
            # redis_selected = {b"14"}
            redis_cart, redis_selected = get_redis_carts(request)

            for sku_id,count in redis_cart.items():
                # sku_id: b'14'
                # count: b'3'
                cart_data[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in redis_selected
                }

        else:
            # 2、未登陆
            # 所有的商品，不管有没有选中
            cart_data = get_carts_from_cookies(request)


        # 构建响应数据
        cart_skus = []
        sku_ids = cart_data.keys() # [14, 16]
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            # sku：模型类对象
            # 只有当前sku商品是选中状态，才返回
            if cart_data[sku.id]['selected']:
                cart_skus.append({
                    'id': sku.id,
                    'name': sku.name,
                    'default_image_url': sku.default_image_url,
                    'count': cart_data[sku.id]['count']
                })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })